package com.yuanian.timingwheel.model.timingwheel;

import com.yuanian.timingwheel.model.slot.Slot;
import com.yuanian.timingwheel.model.task.base.BaseTask;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 秒级时间轮
 */
public class SecondTimingWheel {
    //当前轮次
    private int round;
    //槽数
    private int size;
    //当前秒
    private int tick;
    //槽
    private Map<Integer, Slot> slots;

    public SecondTimingWheel(int round) {
        this.round = round;
        this.size = 60;
        this.tick = 0;
        this.slots = new HashMap(size);
    }

    /**
     * 获取槽位
     * @param index
     * @return
     */
    private Slot getAndSetSlot(int index) {
        if (index < 0 || index > this.size - 1) {
            return null;
        }

        Slot slot = slots.get(index);
        if (slot == null) {
            slot = new Slot();
            slots.put(index, slot);
        }
        return slot;
    }

    private Slot getSlot(int index) {
        if (index < 0 || index > this.size - 1) {
            return null;
        }
        return slots.get(index);
    }

    /**
     * 添加任务
     * @param task
     */
    public void addTask(BaseTask task, int passedMinute) {
        long hour = passedMinute / 60;
        long minute = passedMinute - hour * 60;
        Integer slotNum = getSlotNum(task);
        System.out.println("addTask:执行任务的" + hour + "小时" + minute + "分钟" + slotNum + "秒钟");
        getAndSetSlot(slotNum).push(task);
    }

    private Integer getSlotNum(BaseTask task) {
        Long executionTime = (task.getTaskInfo().getExecutionTime().getTime() / 1000) % 60;
        return executionTime.intValue();
    }

    public void trigger(int slotNum) {
        //此秒加入已经执行集合
        Slot slot = getSlot(slotNum);
        if (slot != null) {
            slot.executeTask();
            slots.remove(slotNum);
        }
    }

}
